package com.sskj.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sskj.api.domain.Department;
import com.sskj.api.exception.LogicException;
import com.sskj.api.mapper.DepartmentMapper;
import com.sskj.api.service.ISysUserService;
import com.sskj.api.service.IDepartmentService;
import com.sskj.common.dto.TreeNode;
import com.sskj.common.util.TreeNodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class DepartmentService extends ServiceImpl<DepartmentMapper, Department> implements IDepartmentService {

    @Autowired
    private ISysUserService adminUserService;

    @Override
    public void add(Department department) {
        LambdaQueryWrapper<Department> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Department::getPid, department.getPid())
                .eq(Department::getName, department.getName());
        if (count(lambdaQueryWrapper) > 0) {
            throw new LogicException("部门已存在");
        }
        department.setCreateTime(LocalDateTime.now());
        save(department);
    }

    @Override
    public void deleteById(Long id) {
        Long count = adminUserService.countByDepartmentId(id);
        if (count > 0) {
            throw new LogicException("部门存在用户，中止操作");
        }
        removeById(id);
    }

    @Override
    public void update(Department department) {
        LambdaQueryWrapper<Department> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.ne(Department::getId, department.getId())
                .eq(Department::getPid, department.getPid())
                .eq(Department::getName, department.getName());
        if (count(lambdaQueryWrapper) > 0) {
            throw new LogicException("部门已存在");
        }

        department.setUpdateTime(LocalDateTime.now());
        updateById(department);
    }

    @Override
    public List<TreeNode<Department>> tree() {
        LambdaQueryWrapper<Department> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByAsc(Department::getPid).orderByAsc(Department::getSortOrder);
        List<Department> all = list(lambdaQueryWrapper);

        if (all != null && !all.isEmpty()) {
            List<TreeNode<Department>> nodes = all.stream().map(item -> {
                TreeNode<Department> node = new TreeNode<>();
                node.setSource(item);
                node.setId(item.getId());
                node.setPid(item.getPid());
                node.setName(node.getName());

                return node;
            }).toList();

            return TreeNodeUtil.buildTree(nodes, 0L);
        }

        return null;
    }
}
